/**
 * 
 */
package com.m7012e.a_remote.ar_listeners.network.protocol;

import java.io.IOException;

import com.leoj.utils.Handler;
import com.leoj.utils.tcp_network.ApplicationProtocol;
import com.leoj.utils.tcp_network.TcpConnection;
import com.m7012e.a_remote.ar_listeners.exception.WrongMessageProtocolException;
import com.m7012e.a_remote.ar_listeners.network.protocol.internEvents.CommunicationOver;
import com.m7012e.a_remote.communication.tcpMessages.DisplayRequestMessage;
import com.m7012e.a_remote.communication.tcpMessages.EndofDisplayMessage;
import com.m7012e.a_remote.communication.tcpMessages.OkMessage;

/**
 * @author leoj
 *
 */
public class DaemonDisplayProtocol implements ApplicationProtocol{

	private Handler<CommunicationOver> _listener;
	
	/**
	 * 
	 */
	public DaemonDisplayProtocol(Handler<CommunicationOver> listener) {
		_listener = listener;
	}
	
	/* (non-Javadoc)
	 * @see com.leoj.utils.tcp_network.ApplicationProtocol#handleClient(com.leoj.utils.tcp_network.TcpConnection)
	 */
	@Override
	public void handleClient(TcpConnection client) {
		System.out.println("DaemonDisplayProtocol is called to handle a new Client connection");
		try {
			Object o = client.read();
			if(! (o instanceof DisplayRequestMessage)){
				overCommunication();
				throw new WrongMessageProtocolException();
			}
			DisplayRequestMessage msg = (DisplayRequestMessage) o;
			System.out.println("Starting to show the diaporama available at this url : "+msg.displayUrl);
			System.out.println("(well for now we display nothing but it will come .. )");
			System.out.println("time to acknowledge !");
			client.send(new OkMessage());
			System.out.println("now wait until we recieve a EndofDisplayMessage");
			o = client.read();
			if(!(o instanceof EndofDisplayMessage)){
				overCommunication();
				throw new WrongMessageProtocolException();
			}
//			EndofDisplayMessage endMsg = (EndofDisplayMessage) o;
			System.out.println("time to over this ! see you !");
			client.close();
			overCommunication();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally{
			overCommunication();
		}
	}

	private void overCommunication(){
		_listener.handle(new CommunicationOver());
	}
}
